import requests
import hashlib
import json
import time
from logger_config import logger

class OpenAIClient:
    def __init__(self):
        self.base_url = "https://io.xxxx.cn/chat/query"
        self.auth_header = {
            'Authorization': 'Basic xxxxxx=',
            'Content-Type': 'application/json'
        }
        self.default_params = {
            "temperature": "1.0",
            "maxTokens": "0.5",
            "topP": "0.5",
            "frequencyPenalty": "0",
            "presencePenalty": "0"
        }

    def _generate_trace_id(self):
        """Generate a unique trace ID using timestamp and md5"""
        timestamp = str(int(time.time() * 1000))
        md5 = hashlib.md5(timestamp.encode()).hexdigest()
        return md5

    def query(self, user_id, content):
        """
        Send query to OpenAI API
        
        Args:
            user_id (str): User ID for the request
            content (str): Content of the query
            
        Returns:
            str: Answer from the API or error message
        """
        payload = {
            "traceId": self._generate_trace_id(),
            "version": "1.0",
            "reqData": {
                "userId": user_id,
                "content": content,
                **self.default_params
            }
        }

        try:
            logger.info(f"OpenAI API Request - User: {user_id}, Content: {content}")
            logger.info(f"Request payload: {json.dumps(payload, ensure_ascii=False)}")
            
            response = requests.post(
                self.base_url,
                headers=self.auth_header,
                json=payload
            )
            response.raise_for_status()
            response_data = response.json()
            
            logger.info(f"API Response: {json.dumps(response_data, ensure_ascii=False)}")
            
            # Check if response is successful and contains answer
            if response_data.get("code") == 200 and response_data.get("resData"):
                answer = response_data["resData"].get("answer", "")
                logger.info(f"OpenAI API Success - Answer received for user {user_id}")
                return answer
            else:
                error_msg = f"Error: {response_data.get('msg', 'Unknown error')}"
                logger.error(f"OpenAI API Error - {error_msg}")
                return None
        except requests.exceptions.RequestException as e:
            error_msg = f"Error: {str(e)}"
            logger.error(f"OpenAI API Request Failed - {error_msg}", exc_info=True)
            return None

# Example usage:
if __name__ == "__main__":
    client = OpenAIClient()
    answer = client.query("13910101010", "说说长城吧，要安排多久活动")
    print("Answer:", answer)
